<template>
  <div class="smart-assistant" @click="handleClick">
    <i class="iconfont">&#xea60;</i>
    <span>助手</span>
  </div>
  <transition name="slide">
    <div class="help" v-if="isVisible" ref="helpElementRef">
      <div class="help-top">
        <div class="helpTop-left">
          <i class="iconfont" style="color: #0FF;font-size: 26px">&#xea60;</i>
          <span>智能医疗小助手</span>
        </div>
        <div class="helpTop-right">
          <el-icon @click="handleHistory">
            <Clock />
          </el-icon>
          <el-icon @click="handleFullScreen">
            <FullScreen />
          </el-icon>
          <el-icon @click="handleClose">
            <CloseBold />
          </el-icon>
        </div>
      </div>
      <div class="help-content">
        <div v-if="showHistory" class="history">
          <h3>历史搜索记录</h3>
          <ul>
            <li v-for="(historyItem, index) in history" :key="index" @click="useHistoryItem(historyItem)">
              {{ historyItem }}
            </li>
          </ul>
        </div>
        <div v-else class="smart-content" ref="contentElement">
          <div v-for="(message, index) in messages" :key="index" class="message">
            <span v-if="message.type === 'user'" class="user-message">{{ message.text }}</span>
            <span v-else class="assistant-message">{{ message.text }}</span>
          </div>
        </div>
      </div>
      <div class="smart-search">
        <el-input type="textarea" autosize clearable placeholder="请输入问题，Ctrl+Enter换行，Enter发送" class="search-input"
          v-model="searchQuery" @keydown="handleKeydown" />
        <el-button type="primary" size="default" :icon="Position" @click="handleSearch">发送</el-button>
      </div>
    </div>
  </transition>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, Ref } from 'vue';
import { ElIcon, ElInput, ElButton } from 'element-plus';
import { Clock, FullScreen, CloseBold, Position } from '@element-plus/icons-vue';

interface Message {
  type: 'user' | 'assistant';
  text: string;
}

const isVisible: Ref<boolean> = ref(false);
const searchQuery: Ref<string> = ref('');
const messages: Ref<Message[]> = ref([]);
const ws: Ref<WebSocket | null> = ref(null);
const showHistory: Ref<boolean> = ref(false);
const history: Ref<string[]> = ref([]);
const helpElementRef = ref<HTMLElement | null>(null);//存储help窗口的dom元素
const isFullScreen = ref(false);//控制全屏标志

const handleClick = () => {
  isVisible.value = !isVisible.value;
};

const handleClose = () => {
  isVisible.value = false;
};

const handleHistory = () => {
  showHistory.value = !showHistory.value;
};


//全屏展示
const handleFullScreen = () => {
  const helpElement = helpElementRef.value;
  if (helpElement) {
    if (isFullScreen.value) {
      // 恢复原始大小
      helpElement.style.width = '';
      helpElement.style.height = '';
      helpElement.style.position = '';
      helpElement.style.top = '';
      helpElement.style.left = '';
      helpElement.style.zIndex = '';
    } else {
      // 占满半个屏幕
      helpElement.style.width = '50%';
      helpElement.style.height = '70%';
      helpElement.style.position = 'fixed';
      helpElement.style.top = '70px';
      helpElement.style.left = '25%';
      helpElement.style.zIndex = '1000';
    }
    isFullScreen.value = !isFullScreen.value;
  }
};

//智能搜索
const handleSearch = () => {
  if (searchQuery.value.trim()) {
    sendMessage(searchQuery.value);
    history.value.push(searchQuery.value); // 添加到历史记录
    searchQuery.value = '';
  }
};

//键盘按键
const handleKeydown = (event: Event) => {
  if (event instanceof KeyboardEvent) {
    if (event.key === 'Enter') {
      if (event.ctrlKey) {
        // Handle Ctrl+Enter for new line
        searchQuery.value += '\n';
        event.preventDefault(); // 阻止默认的换行行为
      } else {
        // Handle Enter for sending message
        handleSearch();
      }
    }
  }
};



const sendMessage = (message: string) => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    const messageObj = {
      session: null,
      message: message
    };
    ws.value.send(JSON.stringify(messageObj));
    messages.value.push({ type: 'user', text: message });
  }
};

//接受数据记录搜索历史
const receiveMessage = (event: MessageEvent) => {
  const data = JSON.parse(event.data);
  messages.value.push({ type: 'assistant', text: data.message });
  scrollContentToBottom();
};

const useHistoryItem = (historyItem: string) => {
  searchQuery.value = historyItem;
  handleSearch();
};

const scrollContentToBottom = () => {
  const contentElement = document.querySelector('.smart-content');
  if (contentElement) {
    contentElement.scrollTop = contentElement.scrollHeight;
  }
};

onMounted(() => {
  isVisible.value = true;

  ws.value = new WebSocket('ws://localhost:8080/ws');

  ws.value.onopen = () => {
    console.log('WebSocket connection opened');
  };

  ws.value.onmessage = receiveMessage;

  ws.value.onclose = () => {
    console.log('WebSocket connection closed');
  };

  ws.value.onerror = (error: Event) => {
    console.error('WebSocket error:', error);
  };
});

onUnmounted(() => {
  if (ws.value) {
    ws.value.close();
  }
});
</script>

<style scoped lang="scss">
.smart-assistant {
  position: fixed;
  bottom: 140px;
  right: 20px;
  background-color: #fff;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 8px;
  /* 圆角 */
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  /* 文字在图标下面 */
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  /* 更深的阴影 */
  cursor: pointer;
  transition: background-color 0.3s ease, transform 0.3s ease;
  /* 添加过渡效果 */

  .iconfont {
    font-size: 12px;
    color: #44d3ef;
    transition: transform 0.3s ease;
    /* 添加图标放大过渡效果 */
  }

  span {
    font-size: 12px;
    color: #0d1216;
    margin-top: 5px;
    /* 图标和文字之间的间距 */
  }

  &:hover {
    background-color: #f0f0f0;
    transform: scale(1.1);

    /* 悬浮时放大按钮 */
    i {
      transform: scale(1.2);
      /* 悬浮时放大图标 */
    }
  }
}

.help {
  position: fixed;
  bottom: 140px;
  right: 90px;
  width: 350px;
  /* 调整宽度 */
  height: 350px;
  /* 调整高度 */
  border-radius: 8px;
  /* 圆角 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  /* 更深的阴影 */
  padding: 20px;
  transition: opacity 0.3s ease, transform 0.3s ease;
  /* 添加过渡效果 */
  z-index: 1000;
  transform: translateX(20px);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-color: rgb(82, 198, 241);

  .help-top {
    display: flex;
    justify-content: space-between; //左右对齐
    align-items: center; //垂直对齐
    margin-bottom: 10px;
  }

  .helpTop-left {
    display: flex;
    align-items: center;
  }

  .helpTop-left .iconfont {
    cursor: pointer;
    margin-right: 10px;
  }

  .helpTop-right {
    display: flex;
    align-items: center;
  }

  .helpTop-right .el-icon {
    margin-left: 10px;
  }
}

.help-content {
  flex: 1;
  overflow-y: auto;
}

.history {
  padding: 10px;
  background-color: rgb(82, 198, 241);
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 100%;
  overflow-y: auto;
}

.history h3 {
  margin-bottom: 10px;
}

.history ul {
  list-style-type: none;
  padding: 0;
}

.history li {
  padding: 8px 12px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.history li:hover {
  background-color: #f0f0f0;
}

.smart-content {
  height: 200px;
  overflow-y: auto;
  padding: 10px;
}

.message {
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
}

.user-message {
  color: #007bff;
  /* 用户消息颜色 */
  background-color: #e0f7fa;
  /* 用户消息背景色 */
  padding: 8px 12px;
  border-radius: 16px;
  align-self: flex-start;
  /* 用户消息靠左对齐 */
  max-width: 80%;
}

.assistant-message {
  color: #333;
  /* 助手消息颜色 */
  background-color: #f0f0f0;
  /* 助手消息背景色 */
  padding: 8px 12px;
  border-radius: 16px;
  align-self: flex-end;
  /* 助手消息靠右对齐 */
  max-width: 80%;
}

.smart-search {
  display: flex;
  align-items: center;
  padding: 10px;
}

.search-input {
  flex: 1;
  margin-right: 10px;
}

.help-content {
  flex: 1;
}

.smart-search {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.search-input {
  flex: 1;
  margin-right: 10px;
}

.slide-enter-active,
.slide-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.slide-enter-from,
.slide-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

.slide-enter-to,
.slide-leave-from {
  opacity: 1;
  transform: translateX(0);
}
</style>
